package fr.poy.mygluco.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.Extent;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserServiceFactory;

import fr.poy.mygluco.model.Record;
import fr.poy.mygluco.server.editions.XlsLogBook;

@SuppressWarnings("serial")
public class DownloadServlet extends HttpServlet {
	 
	static protected Logger log = Logger.getLogger(DownloadServlet.class.getName()); 
	
	public enum Type{
		 PDF("application/pdf","pdf")
		,EXCEL("application/vnd.ms-excel","xls")
		,XML("application/xml","xml")
		;

		private String contentType;
		private String extension;

		Type(String contentType,String extension) {
			this.contentType = contentType;
			this.extension = extension;
		}

		public String toString() {
			return contentType+" "+extension;
		}

		public String getContentType() {
			return contentType;
		}

		public String getExtension() {
			return extension;
		}  
	}
 
	protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String edition = request.getParameter("type");
//		if("logBookPdf".equals(edition))
//			logBookPdf(request, response);
		if("logBookXls".equals(edition))
			logBookXls(request, response); 
		else if("exportXML".equals(edition))
			exportXML(request, response); 
		
	}
	//TODO XLS export
	private void logBookXls( HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
		ServletOutputStream out = response.getOutputStream();
		try {
			String dateDebut = request.getParameter("dateDebut");
			String dateFin   = request.getParameter("dateFin");
			String rupture   = request.getParameter("rupture");//mois
			List<Record> l =null;
		
			setHeaders("logBook", Type.EXCEL , response);  
			 
			 
			XlsLogBook o = new XlsLogBook(l);
			o.build(); 
		} catch (Exception e) {
			log.log(Level.WARNING,"logBookXls", e); 
			throw new ServletException(e);
		}finally{
			out.close();
		}  
	}
	
	private void exportXML( HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
		setHeaders("MyGluco-export", Type.XML , response);  
		PrintWriter out = response.getWriter();
		try {
			String eml = UserServiceFactory.getUserService().getCurrentUser().getEmail();
			PersistenceManager pm = AppServiceImpl.getPmf().getPersistenceManager(); 
			Extent<Record> l = pm.getExtent(Record.class);//query limited to 1000 
			out.write("<!-- Export Mygluco "+new Date().toString()+" -->\n<IMPORT>\n<BGDATA>");
			for (Record record : l) {
				if(eml.equals(record.getUserEmail()))
				out.write(ImportExport.recordToXml(record));
			} 
			out.write("\n</BGDATA>\n</IMPORT>");
			out.flush();
			l.closeAll();
			pm.close();  
		} catch (Exception e) {
			log.log(Level.WARNING,"export XML", e); 
			throw new ServletException(e);
		}finally{
			out.close();
		}  
}
  
//TODO PDF quand itext ok avec appengine	
//	private void logBookPdf( HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
//		ServletOutputStream out = response.getOutputStream();
//		try {
//			String dateDebut = request.getParameter("dateDebut");
//			String dateFin   = request.getParameter("dateFin");
//			String rupture   = request.getParameter("rupture");//mois
//			List<Record> l =null;
//		
//			setHeaders("logBook", Type.PDF , response);  
//			Document document = new Document(/*PageSize.A4.rotate()*/);
//			document.addAuthor("MyGluco - "+UserServiceFactory.getUserService().getCurrentUser().getEmail());
//   		    PdfWriter writer = PdfWriter.getInstance(document, out);  
//			document.open();
//			PdfLogBook o = new PdfLogBook(document,l);
//			o.build();
//			document.close();  
//		} catch (Exception e) {
//			log.log(Level.WARNING,"logBookPdf", e); 
//			throw new ServletException(e);
//		}finally{
//			out.close();
//		}  
//	}
 

	private void setHeaders(String nom,Type type, HttpServletResponse response){
		response.setContentType(type.getContentType());  
		response.setHeader("Content-Disposition", "Attachment;Filename=\""+nom+"."+type.getExtension() + "\"");
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "must-revalidate");
	}
	 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}
}
